package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"regexp"
	"strings"
)

func recordBatchRemove(domain string) {
	reg := regexp.MustCompile("#.*$")
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		row := reg.ReplaceAllString(s.Text(), "")
		row = strings.TrimSpace(row)
		if len(row) == 0 {
			continue
		}
		fields := strings.Fields(row)
		record := fields[0]
		fmt.Printf("%s.%s ... ", record, domain)
		targets, ok := lookupRecord(domain, record)
		if !ok {
			fmt.Println("not found, skiped")
		} else {
			if len(targets) > 1 {
				fmt.Println("more than 1 records, skiped")
				continue
			}
			err := cli.RemoveRecord(targets[0].ID, domain)
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Printf("removed %d records\n", len(targets))
			}
		}
	}
}

func recordBatchImport(domain string) {
	reg := regexp.MustCompile("#.*$")
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		row := reg.ReplaceAllString(s.Text(), "")
		row = strings.TrimSpace(row)
		if len(row) == 0 {
			continue
		}
		fields := strings.Fields(row)
		if len(fields) < 3 {
			fmt.Printf("Error line %s...\n", s.Text())
			continue
		}
		record, t, value := fields[0], fields[1], fields[2]
		var forceAdd bool
		if len(fields) > 3 && fields[3] == "!" {
			forceAdd = true
		}
		fmt.Printf("%s.%s ... ", record, domain)
		targets, ok := lookupRecord(domain, record)
		if !ok || forceAdd {
			_, err := cli.AddRecord(domain, record, t, value)
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println("added")
			}
		} else {
			if len(targets) > 1 {
				fmt.Println("more than 1 record found, skiped")
				continue
			}
			_, err := cli.UpdateRecord(targets[0].ID, domain, record, t, value)
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println("updated")
			}
		}
	}
}

func recordBatch() {
	fs := flag.NewFlagSet("record-batch", flag.ExitOnError)
	fs.Usage = func() {
		fmt.Fprintln(os.Stderr, `Usage: dnspod.cmd record-batch OPTIONS

batch operation for record from stdin, comment start with # symbol

remove=false:
  insert or update mode, if not found record then insert, otherwise update,
  data from stdin like:
#---------------------
test1   A   8.8.8.8   ! # force add
test2   A   1.1.1.1
...
#---------------------

remove=true:
  remove mode, it will remove each record from stdin in first field,
  data from stdin like:
#---------------------
test1 ...
test2 ...
#---------------------

OPTIONS:`)
		fs.PrintDefaults()
	}
	parseCommonArgs(fs)
	domain := fs.String("domain", "", "domain name")
	remove := fs.Bool("remove", false, "remove all sub domains")
	parseArgs(fs)

	if len(confDir) == 0 {
		fmt.Println("Missing conf param")
		os.Exit(1)
	}
	if len(*domain) == 0 {
		fmt.Println("Missing domain param")
		os.Exit(1)
	}

	LoadConf(confDir)

	if *remove {
		recordBatchRemove(*domain)
	} else {
		recordBatchImport(*domain)
	}
}
